/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);

var ids = "";
//表格初始化配置
var tableInit = function () {
    var columns = [
        {
            title: '全选',
            field: 'select',
            //复选框
            checkbox: true,
            width: 25,
            align: 'center',
            valign: 'middle'
        },
        {
            field: 'id',
            title: 'ID',
            align: 'center'
        },
        {
            field: 'showUrl',
            title: '活动封面',
            align: 'center',
            formatter: function (value) {
                if (!empty(value)) {
                    var img_html = "<a href='" + value + "' title='点击查看大图' target='_blank'>" +
                        "<img src='" + value + "' width='40' onerror='imgNotfind(event);' /></a>";
                    return img_html;
                } else {
                    return "<img src='" + value + "' width='40' onerror='imgNotfind(event);' />";
                }
            }
        },
        {
            field: 'title',
            title: '活动标题',
            align: 'center'
        },
        {
            field: 'className',
            title: '活动类别',
            align: 'center'
        },
        {
            field: 'tags',
            title: '活动标签',
            align: 'center',
            formatter: function (value) {
                if (!empty(value)) {
                    arr = value.split(",");
                    var html = "";
                    for (var i = 0; i < arr.length; i++) {
                        if ((i + 1) % 3 == 0) {
                            html = html + '<span class="label label-primary" style="margin:4px 2px;">' + arr[i] + '</span><br /><br />'
                        } else {
                            html = html + '<span class="label label-primary" style="margin:4px 2px;">' + arr[i] + '</span>'
                        }

                    }
                    return html;
                } else {
                    return "暂无";
                }
            }
        },
        {
            field: 'isPush',
            title: '是否发布',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == 0) {
                    return '<span class="label label-warning">未发布</span>';
                } else if (value == 1) {
                    return '<span class="label label-primary">已发布</span>';
                } else if (value == -1) {
                    return '<span class="label label-danger">取消发布</span>';
                } else {
                    return '-';
                }
            }
        }, {
            field: 'isTop',
            title: '是否置顶',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == 0) {
                    return '<span class="label label-warning">不置顶</span>';
                } else if (value == 1) {
                    return '<span class="label label-primary">置顶</span>';
                } else {
                    return '-';
                }
            }
        }, {
            field: 'place',
            title: '活动地点',
            align: 'center'
        }, {
            field: 'tel',
            title: '活动负责人电话',
            align: 'center',
            visible: false,
        }, {
            field: 'signIn',
            title: '签到开始时间',
            align: 'center',
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        }, {
            field: 'beginTime',
            title: '活动开始时间',
            align: 'center',
            visible: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        }, {
            field: 'endTime',
            title: '活动结束时间',
            align: 'center',
            visible: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        }, {
            field: 'maleLimit',
            title: '人数限制人数',
            align: 'center'
        }, {
            field: 'signUpFee',
            title: '报名费用',
            align: 'center',
            visible: false,
            formatter: function (value, row, index) {
                return '<span class="label label-warning">' + value + ' 元/人</span>';
            }
        }, {
            field: 'charge',
            title: '收费说明',
            align: 'center'
        }, {
            field: 'sort',
            title: '排序',
            align: 'center',
            visible: false,
        }, {
            field: 'describe',
            title: '活动描述',
            align: 'center'
        },
        {
            field: 'isBroadcast',
            title: '来源',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == 0) {
                    return '<span class="label label-primary">本校发布</span>';
                } else if (value != null) {
                    return '<span class="label label-warning">广播发布</span>';
                } else {
                    return "-";
                }
            }
        },
        {
            field: 'type',
            title: '场景',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == null) {
                    return '<span class="label label-warning">公用</span>';
                }
                if (value == 1) {
                    return '<span class="label label-primary">面向家长</span>';
                } else if (value == 2) {
                    return '<span class="label label-primary">面向老师</span>';
                } else if (value == 3) {
                    return '<span class="label label-primary">面向校长</span>';
                } else {
                    return "-";
                }
            }
        },
        {
            field: 'schoolId',
            title: '学校',
            align: 'center',
            formatter: function (value, row, index) {
                if (value == null) {
                    return '<span class="label label-warning">公用</span>';
                }
                if (value == schoolId) {
                    return '<span class="label label-primary">'+schoolMap[value]+'</span>';
                } else {
                    return '<span class="label label-warning">'+schoolMap[value]+'</span>';
                }
            }
        },
        {
            field: 'gmtCreate',
            title: '创建时间',
            align: 'center',
            isEnabled: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        },
        {
            field: 'gmtModified',
            title: '更新时间',
            align: 'center',
            isEnabled: false,
            formatter: function (value, row, index) {
                return formatDateTime(value);
            }
        }
    ];

    //请求服务数据时所传参数
    function queryParams(params) {
        return {
            pageNo: params.pageNumber,
            pageSize: params.pageSize,
            companyId:companyId,
            schoolId:schoolId,
            searchText: params.searchText,
            sortName: params.sortName,      //排序列名
            sortOrder: params.sortOrder //排位命令（desc，asc）
        }
    }

    var tableConfig = $.extend(bootstrapTableConfig(_HOST + _API.actArt_activity_list, queryParams, columns), {
        //这里是其他的一些个性化的 bootstrap-table options
        //例如 覆盖一些公共的配置
        //例如 添加一些私有的配置
        showColumns: true,//列显示操作按钮
        ajaxOptions: { //设置自定义请求头
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': 'activity:list'
            }
        },
        //例如格式化数据
        responseHandler: function (res) {
            //在ajax获取到数据，渲染表格之前，修改数据源
            //console.log(res)
            if (res.success) {
                //更新本地token
                sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.token, res.token);
            }
            return res;
        }
    });
    //调用实例化
    $('#bootstrapTableEvents').bootstrapTable(tableConfig);
    $(".search input").attr('placeholder', '输入标题');
};

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['activity:add', 'activity:update', 'activity:delete', 'activity:getUsers',
            'activity:push', 'activity:top', 'activity:cancelPush', 'activity:cancelTop','activity:marketing'],//本页权限数组
        selects: [],
        showBroadcast:false,
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);

            return;
        }
        if (empty(schoolId)) {
            that.showBroadcast = true;
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        // 营销设置
        marketingSetting: function() {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length != 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }
            // 设置链接
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.marketing.getUrl,_HOST + _API.marketing_marketingSeting_getMarketingSetting);
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.marketing.listUrl,_HOST + _API.marketing_couponPush_getCouponPushList);
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.marketing.saveUrl,_HOST + _API.marketing_marketingSeting_save);
            // 设置权限
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.marketing.listAuth,"couponPush:getCouponPushList");
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.marketing.getAuth,"marketingSeting:getMarketingSetting");
            sessionStorageUtils.setJsonStr(storageKey.sessionStorageKey.marketing.saveAuth,"marketingSeting:save");

            var index = layer.open({
                type: 2,
                title: "营销设置",
                content: "../../../../../../public-tools/pc/html/marketing-seting.html?useScene=1&useSceneRelation="+list[0].id,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
                end:function(){//关闭后调用的事件
                    sessionStorageUtils.del(storageKey.sessionStorageKey.marketing.getUrl);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.marketing.listUrl);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.marketing.saveUrl);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.marketing.listAuth);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.marketing.getAuth);
                    sessionStorageUtils.del(storageKey.sessionStorageKey.marketing.saveAuth);
                }
            });
            layer.full(index);
        },
        //添加
        add: function () {
            var that = this;
            //检查可发布活动次数
            Get(that, _HOST + _API.actArt_activity_checkPushActivity + "?companyId=" + companyId )
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response.success) {
                        var index = layer.open({
                            type: 2,
                            title: "新增",
                            content: "edit.html?id=",
                            fix: true,
                            shadeClose: true,
                            shade: false,
                            area: ['70%', '70%'],
                            maxmin: true, //开启最大化最小化按钮
                        });
                        layer.full(index);
                    } else {
                        layer.msg(response.msg, {time: 1500, icon: 5});
                    }
                });
        },
        //修改
        update: function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }
            list = list[0];
            // 判断是否有权操作
            if (!empty(schoolId)) {
                if (schoolId != list.schoolId) {
                    layer.msg('非本校区数据，不可操作!', {time: 1500, icon: 5});
                    return;
                }
            }
            var index = layer.open({
                type: 2,
                title: "修改",
                content: "edit.html?id=" + list.id,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        // 查看报名
        lookSignUp: function() {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0 || list.length > 1) {
                layer.msg('请选中一条数据', {time: 1500, icon: 5});
                return;
            }
            list = list[0];
            // 判断是否有权操作
            if (!empty(schoolId)) {
                if (schoolId != list.schoolId) {
                    layer.msg('非本校区数据，不可操作!', {time: 1500, icon: 5});
                    return;
                }
            }
            var index = layer.open({
                type: 2,
                title: "查看报名",
                content: "../user/list.html?id=" + list.id,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['70%', '70%'],
                maxmin: true, //开启最大化最小化按钮
            });
            layer.full(index);
        },
        // 发布
        push: function () {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }
            ids = "";
            var flag2 = true;
            for (let i = 0; i < list.length; i++) {
                ids += list[i].id;
                if ((i+1)!=list.length) {
                    ids += ",";
                }
                if (!empty(schoolId)) {
                    if (schoolId != list[i].schoolId) {
                        flag2 = false;
                        break;
                    }
                }
            }
            // 判断是否有权操作
            if (!flag2) {
                layer.msg('非本校区数据，不可操作!', {time: 1500, icon: 5});
                return;
            }
            layer.open({
                type: 1,
                content: $('#select')
            });
        },
        // 发布
        pushAct: function(index) {
            var that = this;
            var isBroadcast = $('input[name="isBroadcast"]').filter(':checked').val();
            Post(that, _HOST + _API.actArt_activity_push + "?ids=" + ids + "&isBroadcast=" + isBroadcast, {}, true, that.permissions[index])
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    $('#bootstrapTableEvents').bootstrapTable('refresh');
                    if (response) {
                        if (response.success) {
                            layer.closeAll();
                            layer.msg(response.msg, {time: 1500, icon: 1});
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                });
        },
        // 操作
        del: function (index) {
            var that = this;
            var $result = $('#bootstrapTableEvents');
            var list = $result.bootstrapTable('getSelections');
            if (list.length <= 0) {
                layer.msg('请至少选中一条数据', {time: 1500, icon: 5});
                return;
            }

            var ids = "";
            var flag2 = true;
            for (let i = 0; i < list.length; i++) {
                ids += list[i].id;
                if ((i+1)!=list.length) {
                    ids += ",";
                }
                if (!empty(schoolId)) {
                    if (schoolId != list[i].schoolId) {
                        flag2 = false;
                        break;
                    }
                }
            }
            // 判断是否有权操作
            if (!flag2) {
                layer.msg('非本校区数据，不可操作!', {time: 1500, icon: 5});
                return;
            }

            var info = "";
            var url = "";
            if (index == 2) {
                info = "确定删除选中的活动？";
                url = _HOST + _API.actArt_activity_delete;
            } else if (index == 4) {
                info = "确定发布选中的活动？";
                url = _HOST + _API.actArt_activity_push;
            } else if (index == 5) {
                info = "确定置顶选中的活动？";
                url = _HOST + _API.actArt_activity_top;
            } else if (index == 6) {
                info = "确定取消发布选中的活动？";
                url = _HOST + _API.actArt_activity_cancelPush;
            } else if (index == 7) {
                info = "确定取消置顶选中的活动？";
                url = _HOST + _API.actArt_activity_cancelTop;
            }
            var confirm = layer.confirm(info, {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Post(that, url + "?ids=" + ids, {}, true, that.permissions[index])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        layer.close(confirm);
                        $('#bootstrapTableEvents').bootstrapTable('refresh');
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, {time: 1500, icon: 1});
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                    })
            });

        },
    },
});


$(function () {
    //初始化表格
    tableInit();
});
